<template>
  <div :id="chartId" :style="{ width: chartWidth, height: chartHeight }"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  props: {
    chartId: {
      type: String,
      default: 'lineChart',
    },
    chartWidth: {
      type: String,
      default: '100%',
    },
    chartHeight: {
      type: String,
      default: '100%',
    },
    label: {
      type: Array,
      default: () => ['A', 'B', 'C', 'D', 'E'],
    },
    labelValue: {
      type: Array,
      default: () => [10, 22, 28, 43, 49],
    },
    labelValue2: {
      type: Array,
      default: () => [10, 22, 28, 43, 49],
    },
    dataMap:{
      type:Array
    }
  },
  data() {
    return {
      chart: null,
      newData:{},
    };
  },
  mounted() {
    this.drawLine();
  },
  watch: {
    label: 'drawLine',
    labelValue: 'drawLine',
    labelValue2: 'drawLine',
    dataMap:'drawLine'
  },
  methods: {
    changedata() {
        let keys = [];
        let translationMap = [];
        if (this.chartId === 'id1') {
          keys = ["ph", "temperature","ec", "dissolvedOxygen","ammoniaNitrogen"];
          translationMap = {"ph": "pH值", "temperature": "温度", "ec":"电导率","dissolvedOxygen": "溶解氧","ammoniaNitrogen":"氨氮"};
        } else if (this.chartId === 'id2') {
          keys = ["value", "valueText", "valueEC"];
          translationMap = {"value": "温度", "valueText": "水分", "valueEC": "EC值"};
        } else if (this.chartId === 'id3') {
          keys = ["temp", "humidity", "precip", "pressure"];
          translationMap = {"temp": "空气温度", "humidity": "空气湿度", "precip": "降水量", "pressure": "大气压强"};
        }

        const data = {};
        keys.forEach(key => {
          data[key] = [];
        });

        this.dataMap.forEach(obj => {
          keys.forEach(key => {
            data[key].push(obj[key]);
          });
        });

        keys.forEach(key => {
          this.newData[translationMap[key]] = data[key];
        });
    },
    drawLine() {
      if (Array.isArray(this.dataMap) && this.dataMap.length > 0) {
        this.changedata()
        this.chart = echarts.init(document.getElementById(this.chartId));
        const option = {
          legend: {
            top: 'top',
            data: Object.keys(this.newData)
          },
          xAxis: {
            data: this.dataMap.map(row => row.time)
          },
          yAxis: {},
          series: Object.keys(this.newData).map(key => ({
            name: key,
            data: this.newData[key],
            type: 'line',
            stack: 'x'
          })),
          tooltip: {
            trigger: 'axis'
          },
        };
        // 判断气象的样式默认
        if (this.chartId !== 'id3') {
          option.grid = {
            top: '22%',
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          };
        }
        this.chart.setOption(option);
      }
    },
  },
};
</script>
